﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using WindowsForms.AOnline.Model.BusinessObjects.Dictionary;
using WindowsForms.AOnline.Model.BusinessObjects.Inventory;
using WindowsForms.AOnline.Presenter.Dictionary.Account;
using WindowsForms.AOnline.Presenter.Dictionary.AutoBusiness;
using WindowsForms.AOnline.Presenter.Dictionary.Customer;
using WindowsForms.AOnline.Presenter.Dictionary.InventoryItem;
using WindowsForms.AOnline.Presenter.Dictionary.Stock;
using WindowsForms.AOnline.Presenter.Dictionary.Vendor;
using WindowsForms.AOnline.Presenter.Dictionary.VoucherType;
using WindowsForms.AOnline.Presenter.Inventory.InputInventory;
using WindowsForms.AOnline.Session;
using WindowsForms.AOnline.View.Dictionary;
using WindowsForms.AOnline.View.Inventory;
using WindowsForms.AOnline.WindowsForm.CommonClass;
using WindowsForms.AOnline.WindowsForm.FormBase;
using WindowsForms.AOnline.WindowsForm.FormBase.PropertyGrid;
using WindowsForms.AOnline.WindowsForm.Resources;

namespace WindowsForms.AOnline.WindowsForm.FormBusiness
{
    public partial class FrmXtraInputInventoryDetail : FrmXtraBaseVoucherDetail, IItemTransactionView, IAccountsView, ICustomersView, IVendorsView, IVoucherTypesView, IAutoBusinesssView, IStocksView, IInventoryItemsView
    {
        #region Presenters

        /// <summary>
        /// The _customers presenter
        /// </summary>
        private readonly InputInventoryPresenter _inputInventoryPresenter;

        /// <summary>
        /// The _currencies presenter
        /// </summary>
        private readonly StocksPresenter _stocksPresenter;

        /// <summary>
        /// The _customers presenter
        /// </summary>
        private readonly CustomersPresenter _customersPresenter;

        /// <summary>
        /// The _vendors presenter
        /// </summary>
        private readonly VendorsPresenter _vendorsPresenter;

        // ---  Grid details  ----------------------------------------------------------------------------------------------------------->>>>>>>>>>>

        /// <summary>
        /// The _budget sources presenter
        /// </summary>
        private readonly InventoryItemsPresenter _inventoryItemsPresenter;

        /// <summary>
        /// The _budget sources presenter
        /// </summary>
        private readonly AccountsPresenter _accountsPresenter;

        /// <summary>
        /// The _voucher types presenter
        /// </summary>
        private readonly VoucherTypesPresenter _voucherTypesPresenter;

        /// <summary>
        /// The _auto business presenter
        /// </summary>
        private readonly AutoBusinesssPresenter _autoBusinessesPresenter;

        #endregion

        #region Repository
        /// <summary>
        /// The _RPS accounting object
        /// </summary>
     //   private RepositoryItemGridLookUpEdit _rpsAccountingObject;

        /// <summary>
        /// The _RPS accounting object view
        /// </summary>
   //     private GridView _rpsAccountingObjectView;

        /// <summary>
        /// The _RPS currency
        /// </summary>
      //  private RepositoryItemGridLookUpEdit _rpsCurrency;
        /// <summary>
        /// The _RPS currency view
        /// </summary>
    //    private GridView _rpsCurrencyView;

        /// <summary>
        /// The _RPS spin edit
        /// </summary>
        private RepositoryItemSpinEdit _rpsSpinEdit;

        /// <summary>
        /// The _RPS account number
        /// </summary>
     //   private RepositoryItemGridLookUpEdit _rpsStock;
        /// <summary>
        /// The _RPS account number view
        /// </summary>
      //  private GridView _rpsStockView;

        // ---  Grid details  ----------------------------------------------------------------------------------------------------------->>>>>>>>>>>

        /// <summary>
        /// The _RPS account number
        /// </summary>
    //    private RepositoryItemGridLookUpEdit _rpsAccountNumber;
        /// <summary>
        /// The _RPS account number view
        /// </summary>
   //     private GridView _rpsAccountNumberView;

        /// <summary>
        /// The _RPS corresponding account number
        /// </summary>
        private RepositoryItemGridLookUpEdit _rpsInventoryItem;
        /// <summary>
        /// The _RPS corresponding account number view
        /// </summary>
        private GridView _rpsInventoryItemView;


        /// <summary>
        /// The _RPS corresponding account number
        /// </summary>
        private RepositoryItemGridLookUpEdit _rpsCorrespondingAccountNumber;
        /// <summary>
        /// The _RPS corresponding account number view
        /// </summary>
        private GridView _rpsCorrespondingAccountNumberView;

        /// <summary>
        /// The _RPS bussiness
        /// </summary>
        private RepositoryItemGridLookUpEdit _rpsBussiness;
        /// <summary>
        /// The _RPS bussiness view
        /// </summary>
        private GridView _rpsBussinessView;

     
        /// <summary>
        /// The _RPS automatic businesses
        /// </summary>
        private RepositoryItemGridLookUpEdit _rpsAutoBusinesses;
        /// <summary>
        /// The _RPS automatic businesses view
        /// </summary>
        private GridView _rpsAutoBusinessesView;



        #endregion

        public FrmXtraInputInventoryDetail()
        {
            InitializeComponent();
            _customersPresenter = new CustomersPresenter(this);
            _vendorsPresenter = new VendorsPresenter(this);
            _accountsPresenter = new AccountsPresenter(this);
            _voucherTypesPresenter = new VoucherTypesPresenter(this);
            _autoBusinessesPresenter = new AutoBusinesssPresenter(this);
            _inventoryItemsPresenter = new InventoryItemsPresenter(this);
            _stocksPresenter = new StocksPresenter(this);
            _inputInventoryPresenter = new InputInventoryPresenter(this);
        }

        #region Override
        /// <summary>
        /// Focuses the control.
        /// </summary>
        protected override void InitControls()
        {
            _rpsSpinEdit = new RepositoryItemSpinEdit();

            //_rpsStock = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsStockView = new GridView();
            //_rpsStock.View = _rpsStockView;
            //_rpsStock.TextEditStyle = TextEditStyles.Standard;
            //_rpsStock.ShowFooter = false;

            _rpsInventoryItem = new RepositoryItemGridLookUpEdit { NullText = "" };
            _rpsInventoryItemView = new GridView();
            _rpsInventoryItem.View = _rpsInventoryItemView;
            _rpsInventoryItem.TextEditStyle = TextEditStyles.Standard;
            _rpsInventoryItem.ShowFooter = false;

            //_rpsAccountingObject = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsAccountingObjectView = new GridView();
            //_rpsAccountingObject.View = _rpsAccountingObjectView;
            //_rpsAccountingObject.TextEditStyle = TextEditStyles.Standard;
            //_rpsAccountingObject.ShowFooter = false;

            //_rpsBudgetItem = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsBudgetItemView = new GridView();
            //_rpsBudgetItem.View = _rpsBudgetItemView;
            //_rpsBudgetItem.TextEditStyle = TextEditStyles.Standard;
            //_rpsBudgetItem.ShowFooter = false;

            //_rpsBudgetSource = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsBudgetSourceView = new GridView();
            //_rpsBudgetSource.View = _rpsBudgetSourceView;
            //_rpsBudgetSource.TextEditStyle = TextEditStyles.Standard;
            //_rpsBudgetSource.ShowFooter = false;

            _rpsCorrespondingAccountNumber = new RepositoryItemGridLookUpEdit { NullText = "" };
            _rpsCorrespondingAccountNumberView = new GridView();
            _rpsCorrespondingAccountNumber.View = _rpsCorrespondingAccountNumberView;
            _rpsCorrespondingAccountNumber.TextEditStyle = TextEditStyles.Standard;
            _rpsCorrespondingAccountNumber.ShowFooter = false;

            //_rpsCurrency = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsCurrencyView = new GridView();
            //_rpsCurrency.View = _rpsCurrencyView;
            //_rpsCurrency.TextEditStyle = TextEditStyles.Standard;
            //_rpsCurrency.ShowFooter = false;

            //_rpsMergerFund = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsMergerFundView = new GridView();
            //_rpsMergerFund.View = _rpsMergerFundView;
            //_rpsMergerFund.TextEditStyle = TextEditStyles.Standard;
            //_rpsMergerFund.ShowFooter = false;

            //_rpsProject = new RepositoryItemGridLookUpEdit { NullText = "" };
            //_rpsProjectView = new GridView();
            //_rpsProject.View = _rpsProjectView;
            //_rpsProject.TextEditStyle = TextEditStyles.Standard;
            //_rpsProject.ShowFooter = false;

            _rpsBussiness = new RepositoryItemGridLookUpEdit { NullText = "" };
            _rpsBussinessView = new GridView();
            _rpsBussiness.View = _rpsBussinessView;
            _rpsBussiness.TextEditStyle = TextEditStyles.Standard;
            _rpsBussinessView.OptionsView.ShowColumnHeaders = false;
            _rpsBussiness.ShowFooter = false;

            _rpsAutoBusinesses = new RepositoryItemGridLookUpEdit { NullText = "" };
            _rpsAutoBusinessesView = new GridView();
            _rpsAutoBusinesses.View = _rpsAutoBusinessesView;
            _rpsAutoBusinesses.TextEditStyle = TextEditStyles.Standard;
            _rpsAutoBusinesses.ShowFooter = false;

            grdObjectCode.Properties.TextEditStyle = TextEditStyles.Standard;
        }

        /// <summary>
        /// Initializes the data.
        /// </summary>
        protected override void InitData()
        {
            InitObjectCategory();
          //  InitGridMain();
            if (ActionMode == ActionModeEnum.None)
            {
                if (MasterBindingSource.Current != null)
                {
                    var paymentVoucherId = ((ItemTransactionModel)MasterBindingSource.Current).RefId;
                    KeyValue = paymentVoucherId.ToString(CultureInfo.InvariantCulture);
                }
            }
            if (KeyValue == null)
            {
                ItemTransactionDetails = new List<ItemTransactionDetailModel>();
                AccountingObjectType = -1;
                grdObjectCode.Enabled = false;
            }

            //Fill data to combobox  --------------------------------------
            //_accountsPresenter.DisplayInventoryItem();
            _accountsPresenter.GetAll();
            _inventoryItemsPresenter.GetAll(); //Display
            _stocksPresenter.GetAll();
            _voucherTypesPresenter.Display();
            _autoBusinessesPresenter.GetAll();
            if (KeyValue != null)
            {
                _inputInventoryPresenter.Display(long.Parse(KeyValue));
                if (ActionMode == ActionModeEnum.AddNew)
                {
                    KeyValue = null;
                    RefId = 0;
                    AccountingObjectType = -1;
                    grdObjectCode.Text = @"";
                    txtDescription.Text = "";
                    txtContactName.Text = "";
                    grdObjectCode.Enabled = false;
                  //  InitGridMain();
                    ItemTransactionDetails = new List<ItemTransactionDetailModel>();
                }
            }
        }

        /// <summary>
        /// Valids the data.
        /// </summary>
        /// <returns></returns>
        protected override bool ValidData()
        {
            var flag = true;
            var resourceName = string.Empty;
            switch (AccountingObjectType)
            {
                case -1:
                    {
                        resourceName = "ResObjectId";
                        flag = false;
                        break;
                    }
                case 3:
                    {
                        if (CustomerId != null) break;
                        resourceName = "ResCustomerId";
                        flag = false;
                        break;

                    }
                case 0:
                    {
                        if (VendorId != null) break;
                        resourceName = "ResVendorId";
                        flag = false;
                        break;
                    }
            }
            if (!flag)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName(resourceName),
                           ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                           MessageBoxIcon.Error);
                grdObjectCode.Focus();
                return false;
            }
            if (RefNo.Length == 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResRefNo"),
                       ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
                txtRefNo.Focus();
                return false;
            }
            //if (dtRefDate.DateTime < DateTime.Parse(GlobalVariable.SystemDate))
            //{
            //    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResRefDate"),
            //           ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
            //           MessageBoxIcon.Error);
            //    dtRefDate.Focus();
            //    return false;
            //}
            //if (dtPostDate.DateTime < DateTime.Parse(GlobalVariable.SystemDate))
            //{
            //    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResPostDate"),
            //           ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
            //           MessageBoxIcon.Error);
            //    dtPostDate.Focus();
            //    return false;
            //}
            var itemTransactionDetails = ItemTransactionDetails;
            if (itemTransactionDetails.Count == 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResTotalAmount"),
                       ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
                return false;
            }
          //  var stockCol = gridViewMaster.Columns["StockId"];

            var customer = (StockModel)grdStock.GetSelectedDataRow();
            var stockId = (int)customer.StockId;
           // var stockId = (int)gridViewMaster.GetFocusedRowCellValue(stockCol);
            if (stockId <= 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResStockId"), ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (itemTransactionDetails.Count > 0)
            {
                foreach (var voucher in itemTransactionDetails)
                {
                    //if (voucher.CorrespondingAccountNumber != (string)gridViewMaster.GetFocusedRowCellValue("AccountNumber"))
                    //{
                    //    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResAccountNumberCompareMaster"),
                    //   ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                    //   MessageBoxIcon.Error);
                    //    return false;
                    //}
                    //if (voucher.AccountNumber == null)
                    //{
                    //    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResAccountNumber"),
                    //   ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                    //   MessageBoxIcon.Error);
                    //    return false;
                    //}
                    if (voucher.InventoryItemId == 0)
                    {
                        XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResInventoryItemCode"),
                       ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Saves the data.
        /// </summary>
        /// <returns></returns>
        protected override string SaveData()
        {
            //if (ActionMode == ActionModeEnum.Edit)
            //    RefId = (_keyForSend == null || long.Parse(_keyForSend) == 0) ? RefId : long.Parse(_keyForSend);
            //if (ActionMode == ActionModeEnum.AddNew || ActionMode == ActionModeEnum.DuplicateVoucher)
            //    RefId = 0;
            return _inputInventoryPresenter.Save();
        }

        /// <summary>
        /// Deletes the voucher.
        /// </summary>
        protected override string DeleteVoucher()
        {
            var refId = RefId ;//> 0 ? RefId : long.Parse(_keyForSend);
           return _inputInventoryPresenter.Delete(refId);
        }

        #endregion

        #region User Function
        /// <summary>
        /// Objects the categorys.
        /// </summary>
        /// <returns></returns>
        protected IList<ObjectCategory> ObjectCategorys()
        {
            IList<ObjectCategory> listOc = new List<ObjectCategory>();
            listOc.Add(new ObjectCategory(0, "Nhà cung cấp"));
            //listOc.Add(new ObjectCategory(1, "Nhân viên"));
            //listOc.Add(new ObjectCategory(2, "Đối tượng khác"));
            listOc.Add(new ObjectCategory(3, "Khách hàng"));
            return listOc;
        }

   

        /// <summary>
        /// Initializes the object category.
        /// </summary>
        protected void InitObjectCategory()
        {
            cboObjectCategory.Properties.DataSource = ObjectCategorys();
            cboObjectCategory.Properties.PopulateColumns();
            var treeColumnsCollection = new List<LookUpColumnInfo>
                {
                    new LookUpColumnInfo
                        {
                            FieldName = "ObjectCategoryId",                            
                            Visible = false                            
                        },
                    new LookUpColumnInfo
                        {
                            FieldName = "ObjectCategoryName",
                            Visible = true,
                            Width = 50,
                            Caption = @"Tên loại đối tượng",
                        }
                };
            foreach (var column in treeColumnsCollection)
            {
                if (column.Visible)
                {
                    cboObjectCategory.Properties.Columns[column.FieldName].Caption = column.Caption;
                }
                else cboObjectCategory.Properties.Columns[column.FieldName].Visible = false;
            }
            cboObjectCategory.Properties.ValueMember = "ObjectCategoryId";
            cboObjectCategory.Properties.DisplayMember = "ObjectCategoryName";
            cboObjectCategory.Properties.ShowFooter = false;
            cboObjectCategory.Properties.ShowHeader = false;
        }

     
        #endregion

        #region Property

        public long RefId
        {
            get;
            set;
        }

        public int RefTypeId
        {
            get { return 400; }// (int)BaseRefTypeId; }
            set
            {
                BaseRefTypeId = (RefType)value;
            }
        }

        public string RefNo
        {
            get { return txtRefNo.Text; }
            set { txtRefNo.Text = value; }
        }

        public string RefDate
        {
            get
            {
                var refDate = (DateTime)dtRefDate.EditValue;
                var now = DateTime.Now;
                var newDate = new DateTime(refDate.Year, refDate.Month, refDate.Day, now.Hour, now.Minute, now.Second);
                return dtRefDate.EditValue == null ? null : newDate.ToString("dd/MM/yyyy");
            }
            set
            {
                dtRefDate.EditValue = DateTime.Parse(value);
            }
        }

     

     
        public int? CustomerId
        {
            get
            {
                if (AccountingObjectType == 3)
                {
                    var customer = (CustomerModel)grdObjectCode.GetSelectedDataRow();
                    if (customer != null)
                        return customer.CustomerId;
                }
                return null;
            }
            set
            {
                if (AccountingObjectType == 3)
                {
                    if (value != null)
                        grdObjectCode.EditValue = value;
                }
            }
        }

        public int? VendorId
        {
            get
            {
                if (AccountingObjectType == 0)
                {
                    var vendor = (VendorModel)grdObjectCode.GetSelectedDataRow();
                    if (vendor != null)
                        return (int)vendor.VendorId;
                }
                return null;
            }
            set
            {
                if (AccountingObjectType == 0)
                {
                    if (value != null)
                        grdObjectCode.EditValue = value;
                }
            }
        }

      

        public string Trader
        {
            get { return txtContactName.Text; }
            set { txtContactName.Text = value; }
        }

        public string TaxCode
        {
            get { return txtTaxCode.Text; }
            set { txtTaxCode.Text = value; }
        }

       

        public int StockId
        {
            get
            {

                var customer = (StockModel)grdStock.GetSelectedDataRow();
                        return (int)customer.StockId;
            }
            set
            {

                        grdStock.EditValue = value;

            }
        }





        public string JournalMemo
        {
            get { return txtDescription.Text; }
            set { txtDescription.Text = value; }
        }

        public string DocumentInclude
        {
            get { return txtDocumentInclude.Text; }
            set { txtDocumentInclude.Text = value; }
        }

        public int? AccountingObjectType
        {
            get
            {
                var objId = cboObjectCategory.GetColumnValue("ObjectCategoryId");
                if (objId != null)
                    return (int)objId;
                return -1;
            }
            set
            {
                cboObjectCategory.EditValue = value ?? -1;
                switch (AccountingObjectType)
                {
                    case 3:
                        _customersPresenter.GetAll();
                        break;
                    case 0:
                        _vendorsPresenter.GetAll();
                        break;
                    case 1:
                     //   _employeesPresenter.Display();
                        break;
                    case 2:
                    //    _accountingObjectsPresenter.DisplayActive(false);
                        break;
                    case -1:
                        {
                            cboObjectCategory.EditValue = -1;
                            break;
                        }
                }
            }
        }

        public long UnitId
        {
            get;

            set;
           
        }

        public decimal TotalAmountOc
        {

              get;

            set;

            //get
            //{
            //    gridViewMaster.PostEditor();
            //    return (decimal)gridViewMaster.GetFocusedRowCellValue("ExchangeRate");
            //}
            //set
            //{
            //    var rowHandle = gridViewMaster.FocusedRowHandle;
            //    gridViewMaster.SetRowCellValue(rowHandle, "ExchangeRate", value);
            //}
        }

        public decimal TotalAmountTax
        {

              get;

            set;

            //get
            //{
            //    gridViewMaster.PostEditor();
            //    return (decimal)gridViewMaster.GetFocusedRowCellValue("ExchangeRate");
            //}
            //set
            //{
            //    var rowHandle = gridViewMaster.FocusedRowHandle;
            //    gridViewMaster.SetRowCellValue(rowHandle, "ExchangeRate", value);
            //}
        }
        public IList<Model.BusinessObjects.Inventory.ItemTransactionDetailModel> ItemTransactionDetails
        {
            get
            {
                var itemTransactionDetailModel = new List<ItemTransactionDetailModel>();
                if (gridViewDetail.DataSource != null && gridViewDetail.RowCount > 0)
                {
                    decimal totalAmount = 0;
                    decimal totalAmountExchange = 0;
                    for (var i = 0; i < gridViewDetail.RowCount; i++)
                    {
                        var rowVoucherDetailData = (ItemTransactionDetailModel)gridViewDetail.GetRow(i);
                        if (rowVoucherDetailData != null)
                        {
                            var item = new ItemTransactionDetailModel
                            {
                                AccountNumber = rowVoucherDetailData.AccountNumber,
                                AccountNumberVat = rowVoucherDetailData.AccountNumberVat,
                                CorrespondingAccountNumber =
                                    rowVoucherDetailData.CorrespondingAccountNumber,
                                Description = rowVoucherDetailData.Description,
                                AmountOc = rowVoucherDetailData.AmountOc,
                                AmountVat = rowVoucherDetailData.AmountVat,
                                TaxRate = rowVoucherDetailData.TaxRate,
                             
                                VoucherTypeId = rowVoucherDetailData.VoucherTypeId == 0 ? null : rowVoucherDetailData.VoucherTypeId,
                             
                                InventoryItemId = rowVoucherDetailData.InventoryItemId,
                                Quantity = rowVoucherDetailData.Quantity,
                                Price = rowVoucherDetailData.Price
                            };
                            totalAmount += item.AmountOc;
                            itemTransactionDetailModel.Add(item);
                        }
                    }
                    TotalAmountOc = totalAmount;
                    TotalAmountTax = totalAmountExchange;
                }
                return itemTransactionDetailModel.ToList();
            }
            set
            {
                ColumnsCollection.Clear();
                bindingSourceDetail.DataSource = value.Count == 0 ? new List<ItemTransactionDetailModel> { new ItemTransactionDetailModel { CorrespondingAccountNumber = "111" } } : value;
                gridViewDetail.PopulateColumns(value);
                ColumnsCollection.Add(new XtraColumn { ColumnName = "ItemTransactionDetailId", ColumnVisible = false, Alignment = HorzAlignment.Center });
                ColumnsCollection.Add(new XtraColumn
                {
                    ColumnName = "AutoBusinessId",
                    ColumnCaption = "ĐK tự động",
                    ToolTip = "Định khoản tự động",
                    ColumnPosition = 1,
                    ColumnVisible = true,
                    ColumnWith = 100,
                    FixedColumn = FixedStyle.Left,
                    AllowEdit = true
                });
                ColumnsCollection.Add(new XtraColumn { ColumnName = "InventoryItemId", FixedColumn = FixedStyle.Left, ColumnCaption = "Vật tư", ToolTip = "Vật tư", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 100 });
                ColumnsCollection.Add(new XtraColumn { ColumnName = "AccountNumber", FixedColumn = FixedStyle.Left, ColumnCaption = "TK Nợ", ToolTip = "Tài khoản nợ", ColumnPosition = 3, ColumnVisible = true, ColumnWith = 100 });
                ColumnsCollection.Add(new XtraColumn { ColumnName = "CorrespondingAccountNumber", FixedColumn = FixedStyle.Left, ColumnCaption = "TK Có", ToolTip = "Tài khoản có", ColumnPosition = 4, ColumnVisible = true, ColumnWith = 100 });

               


                ColumnsCollection.Add(new XtraColumn { ColumnName = "Description", FixedColumn = FixedStyle.None, ColumnCaption = "Diễn giải", ColumnPosition = 5, ColumnVisible = true, ColumnWith = 200 });

                ColumnsCollection.Add(new XtraColumn { ColumnName = "Quantity", FixedColumn = FixedStyle.None, ColumnType = UnboundColumnType.Integer, ColumnCaption = "Số lượng", ColumnPosition = 6, ColumnVisible = true, ColumnWith = 80 });
                ColumnsCollection.Add(new XtraColumn { ColumnName = "Price", FixedColumn = FixedStyle.None, ColumnType = UnboundColumnType.Decimal, ColumnCaption = "Đơn giá", ColumnPosition = 7, ColumnVisible = true, ColumnWith = 100 });

              
                ColumnsCollection.Add(new XtraColumn { ColumnName = "AmountOc", FixedColumn = FixedStyle.None, ColumnType = UnboundColumnType.Decimal, ColumnCaption = "Thành tiền", ColumnPosition = 8, ColumnVisible = true, ColumnWith = 100 });

                ColumnsCollection.Add(new XtraColumn { ColumnName = "AccountNumberVat", FixedColumn = FixedStyle.Left, ColumnCaption = "TK Có VAT", ToolTip = "Tài khoản có VAT", ColumnPosition = 9, ColumnVisible = true, ColumnWith = 100 });

                ColumnsCollection.Add(new XtraColumn { ColumnName = "TaxRate", FixedColumn = FixedStyle.None, ColumnType = UnboundColumnType.Decimal, ColumnCaption = "% thuế VAT", ColumnPosition = 10, ColumnVisible = true, ColumnWith = 100 });
                ColumnsCollection.Add(new XtraColumn { ColumnName = "AmountVat", FixedColumn = FixedStyle.None, ColumnType = UnboundColumnType.Decimal, ColumnCaption = "Tiền VAT", ColumnPosition = 11, ColumnVisible = true, ColumnWith = 100 });
              
                ColumnsCollection.Add(new XtraColumn { ColumnName = "VoucherTypeId", FixedColumn = FixedStyle.None, ColumnCaption = "Nghiệp vụ", ColumnPosition = 12, ColumnVisible = true, ColumnWith = 150 });
      

                ColumnsCollection.Add(new XtraColumn { ColumnName = "RefId", ColumnVisible = false });
                foreach (var column in ColumnsCollection)
                {
                    if (column.ColumnVisible)
                    {
                        gridViewDetail.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        gridViewDetail.Columns[column.ColumnName].VisibleIndex = column.ColumnPosition;
                        gridViewDetail.Columns[column.ColumnName].Width = column.ColumnWith;
                        gridViewDetail.Columns[column.ColumnName].Fixed = column.FixedColumn;
                        gridViewDetail.Columns[column.ColumnName].ToolTip = column.ToolTip;
                        switch (column.ColumnName)
                        {
                            case "AutoBusinessId":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsAutoBusinesses;
                                break;
                            case "AccountNumber":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsCorrespondingAccountNumber;
                                break;
                            case "CorrespondingAccountNumber":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsCorrespondingAccountNumber;
                                break;

                            case "AccountNumberVat":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsCorrespondingAccountNumber;
                                break;

                            case "VoucherTypeId":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsBussiness;
                                break;
                            case "InventoryItemId":
                                gridViewDetail.Columns[column.ColumnName].ColumnEdit = _rpsInventoryItem;
                                break;
                        }
                    }
                    else gridViewDetail.Columns[column.ColumnName].Visible = false;
                }
            }

        }

        #endregion

        #region Param Master

        /// <summary>
        /// Sets the stocks.
        /// </summary>
        /// <value>
        /// The stocks.
        /// </value>
        public IList<StockModel> Stocks
        {
            set
            {
                grdStock.Properties.DataSource = value;
                grdStock.Properties.PopulateViewColumns();
                var colColection = new List<XtraColumn>();
                colColection.Clear();

                colColection.Add(new XtraColumn { ColumnName = "StockCode", ColumnCaption = "Mã kho", ToolTip = "Mã kho", ColumnPosition = 1, ColumnVisible = true, ColumnWith = 100, Alignment = HorzAlignment.Center });
                colColection.Add(new XtraColumn { ColumnName = "StockName", ColumnCaption = "Tên kho", ToolTip = "Tên kho", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 100, Alignment = HorzAlignment.Center });
                colColection.Add(new XtraColumn { ColumnName = "StockId", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "IsActive", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "Description", ColumnCaption = "", ColumnVisible = false });
                foreach (var column in colColection)
                {
                    if (column.ColumnVisible)
                    {
                        grdStock.Properties.View.Columns[column.ColumnName].ToolTip = column.ToolTip;
                        grdStock.Properties.View.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdStock.Properties.View.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                        grdStock.Properties.View.Columns[column.ColumnName].Width = column.ColumnWith;
                    }
                    else grdStock.Properties.View.Columns[column.ColumnName].Visible = false;
                }
                grdStock.Properties.BestFitMode = BestFitMode.BestFitResizePopup;
                grdStock.Properties.View.OptionsView.ShowIndicator = false;
                grdStock.Properties.View.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                grdStock.Properties.DisplayMember = "StockCode";
                grdStock.Properties.ValueMember = "StockId";
            }
        }

        
        /// <summary>
        /// Sets the customers.
        /// </summary>
        /// <value>
        /// The customers.
        /// </value>
        public IList<CustomerModel> Customers
        {
            set
            {
                grdObjectCode.Properties.DataSource = value;
                gridLookUpEdit1View.PopulateColumns(value);
                var customerColumns = new List<XtraColumn>();
                customerColumns.Add(new XtraColumn { ColumnName = "CustomerId", ColumnVisible = false, Alignment = HorzAlignment.Center });
                customerColumns.Add(new XtraColumn { ColumnName = "Code", ColumnCaption = "Mã KH", ToolTip = "Mã khách hàng", ColumnPosition = 1, ColumnVisible = true, ColumnWith = 100 });
                customerColumns.Add(new XtraColumn { ColumnName = "Name", ColumnCaption = "Tên khách hàng", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 300 });
                customerColumns.Add(new XtraColumn { ColumnName = "Address", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "IsActive", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "ContactName", ColumnVisible = false });

                customerColumns.Add(new XtraColumn { ColumnName = "PhoneNumber", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "Description", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "UnitId", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "Fax", ColumnVisible = false });
                customerColumns.Add(new XtraColumn { ColumnName = "CompanyName", ColumnVisible = false });
               
                foreach (var column in customerColumns)
                {
                    if (column.ColumnVisible)
                    {
                        grdObjectCode.Properties.View.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        //grdObjectCode.Properties.View.Columns[column.ColumnName].Width = column.ColumnWith;
                    }
                    else grdObjectCode.Properties.View.Columns[column.ColumnName].Visible = false;

                }
                grdObjectCode.Properties.BestFitMode = BestFitMode.BestFitResizePopup;
                grdObjectCode.Properties.View.OptionsView.ShowIndicator = false;
                grdObjectCode.Properties.ValueMember = "CustomerId";
                grdObjectCode.Properties.DisplayMember = "Code";
                grdObjectCode.Properties.ShowFooter = false;
            }
        }

        /// <summary>
        /// Sets the vendors.
        /// </summary>
        /// <value>
        /// The vendors.
        /// </value>
        public IList<VendorModel> Vendors
        {
            set
            {
                grdObjectCode.Properties.DataSource = value;
                gridLookUpEdit1View.PopulateColumns(value);
                var colCollection = new List<XtraColumn>
                                        {
                                            new XtraColumn
                                                {
                                                    ColumnName = "VendorId",
                                                    ColumnVisible = false,
                                                    Alignment = HorzAlignment.Center
                                                },
                                            new XtraColumn
                                                {
                                                    ColumnName = "Code",
                                                    ColumnCaption = "Mã NCC",
                                                    ToolTip = "Mã nhà cung cấp",
                                                    ColumnPosition = 1,
                                                    ColumnVisible = true,
                                                    ColumnWith = 100
                                                },
                                            new XtraColumn
                                                {
                                                    ColumnName = "Name",
                                                    ColumnCaption = "Tên nhà cung cấp",
                                                    ColumnPosition = 1,
                                                    ColumnVisible = true,
                                                    ColumnWith = 300
                                                },
                                            new XtraColumn {ColumnName = "Address", ColumnVisible = false},
                                            new XtraColumn {ColumnName = "IsActive", ColumnVisible = false},
                                            new XtraColumn {ColumnName = "ContactName", ColumnVisible = false},
  
                                            new XtraColumn {ColumnName = "PhoneNumber", ColumnVisible = false},
                                        
                                            new XtraColumn {ColumnName = "UnitId", ColumnVisible = false},
                                            new XtraColumn {ColumnName = "Fax", ColumnVisible = false},
                                           new XtraColumn {ColumnName = "Description", ColumnVisible = false}
                                        };

                foreach (var column in colCollection)
                {
                    if (column.ColumnVisible)
                    {
                        grdObjectCode.Properties.View.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        //grdObjectCode.Properties.View.Columns[column.ColumnName].Width = column.ColumnWith;
                        grdObjectCode.Properties.View.Columns[column.ColumnName].ToolTip = column.ToolTip;
                    }
                    else grdObjectCode.Properties.View.Columns[column.ColumnName].Visible = false;
                }
                grdObjectCode.Properties.BestFitMode = BestFitMode.BestFitResizePopup;
                grdObjectCode.Properties.View.OptionsView.ShowIndicator = false;
                grdObjectCode.Properties.ValueMember = "VendorId";
                grdObjectCode.Properties.DisplayMember = "Code";
                grdObjectCode.Properties.ShowFooter = false;
            }
        }

        

      

        #endregion

        #region Param Details

        /// <summary>
        /// Sets the accounts.
        /// </summary>
        /// <value>
        /// The accounts.
        /// </value>
        public IList<AccountModel> Accounts
        {
            set
            {
                _rpsCorrespondingAccountNumber.DataSource = value;
                _rpsCorrespondingAccountNumber.PopulateViewColumns();
                var rpsAccountColumnCollection = new List<XtraColumn>
                                                   {
                                                       new XtraColumn
                                                           {
                                                               ColumnName = "AccountId",                                                                                                                             
                                                               ColumnVisible = false                                                               
                                                           }, 
                                                            new XtraColumn
                                                           {
                                                               ColumnName = "BalanceSide",                                                                                                                             
                                                               ColumnVisible = false                                                               
                                                           },
                                                       new XtraColumn
                                                           {
                                                               ColumnName = "AccountCode",
                                                               ColumnCaption = "Mã tài khoản",
                                                               ColumnPosition = 1,
                                                               ColumnVisible = true,
                                                               ColumnWith = 100,
                                                               Alignment = HorzAlignment.Center 
                                                           },
                                        
                                                       new XtraColumn
                                                           {
                                                               ColumnName = "AccountName",
                                                               ColumnCaption = "Tên tài khoản",                                                               
                                                               ColumnVisible = true,
                                                               ColumnPosition = 2,
                                                               ColumnWith = 300,
                                                               Alignment = HorzAlignment.Center 
                                                           },
                                                       new XtraColumn
                                                           {
                                                               ColumnName = "Description",                                                               
                                                               ColumnVisible = false                                                               
                                                           },
                                                       new XtraColumn
                                                           {
                                                               ColumnName = "IsActive",                                                               
                                                               ColumnVisible = false,                                                               
                                                           },
                                         
                                                       new XtraColumn {ColumnName = "Grade", ColumnVisible = false},
                                                       new XtraColumn {ColumnName = "IsDetail", ColumnVisible = false},
                                          

                                                       new XtraColumn {ColumnName = "IsSystem", ColumnVisible = false},
                                 

                                                       new XtraColumn
                                                           {ColumnName = "IsInventoryItem", ColumnVisible = false},
                                                       new XtraColumn
                                                           {ColumnName = "IsFixedAsset", ColumnVisible = false},
                                                           new XtraColumn
                                                           {ColumnName = "ParentId", ColumnVisible = false},
                                                                  new XtraColumn
                                                           {ColumnName = "UnitId", ColumnVisible = false},
                                                       new XtraColumn
                                                           {ColumnName = "IsCustomer", ColumnVisible = false},
                                                              new XtraColumn
                                                           {ColumnName = "IsVendor", ColumnVisible = false},
                                                       new XtraColumn {ColumnName = "IsTax", ColumnVisible = false}
                                                   };

                foreach (var column in rpsAccountColumnCollection)
                {
                    if (column.ColumnVisible)
                    {
                        //_rpsAccountNumber.View.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        //_rpsAccountNumber.View.Columns[column.ColumnName].AbsoluteIndex = column.ColumnPosition;

                        _rpsCorrespondingAccountNumber.View.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        _rpsCorrespondingAccountNumber.View.Columns[column.ColumnName].AbsoluteIndex = column.ColumnPosition;
                    }
                    else
                    {
                        //_rpsAccountNumber.View.Columns[column.ColumnName].Visible = false;
                        _rpsCorrespondingAccountNumber.View.Columns[column.ColumnName].Visible = false;
                    }
                }
                //_rpsAccountNumber.BestFitMode = BestFitMode.BestFitResizePopup;
                //_rpsAccountNumber.View.OptionsView.ShowIndicator = false;
                //_rpsAccountNumber.View.ActiveFilterString = "[AccountCode] like '111%'";
                //_rpsAccountNumber.View.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                //_rpsAccountNumber.ValueMember = "AccountCode";
                //_rpsAccountNumber.DisplayMember = "AccountCode";

                _rpsCorrespondingAccountNumber.BestFitMode = BestFitMode.BestFitResizePopup;
                _rpsCorrespondingAccountNumber.View.OptionsView.ShowIndicator = false;
                _rpsCorrespondingAccountNumber.ValueMember = "AccountCode";
                _rpsCorrespondingAccountNumber.DisplayMember = "AccountCode";
            }
        }

       

        /// <summary>
        /// Sets the voucher types.
        /// </summary>
        /// <value>
        /// The voucher types.
        /// </value>
        public IList<VoucherTypeModel> VoucherTypes
        {
            set
            {
                _rpsBussiness.DataSource = value;
                _rpsBussiness.PopulateViewColumns();
                var colColection = new List<XtraColumn>();
                colColection.Clear();

                colColection.Add(new XtraColumn
                {
                    ColumnName = "VoucherTypeId",
                    ColumnCaption = "Mã nghiệp vụ",
                    ColumnPosition = 1,
                    ColumnVisible = false,
                    ColumnWith = 100,
                    Alignment = HorzAlignment.Center
                });
                colColection.Add(new XtraColumn
                {
                    ColumnName = "VoucherTypeName",
                    ColumnCaption = "Tên nghiệp vụ",
                    ColumnPosition = 2,
                    ColumnVisible = true,
                    ColumnWith = 300,
                    Alignment = HorzAlignment.Center
                });
                colColection.Add(new XtraColumn { ColumnName = "IsActive", ColumnVisible = false });
                foreach (var column in colColection)
                {
                    if (column.ColumnVisible)
                    {
                        _rpsBussinessView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        _rpsBussinessView.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                        _rpsBussinessView.Columns[column.ColumnName].Width = column.ColumnWith;
                    }
                    else _rpsBussinessView.Columns[column.ColumnName].Visible = false;
                }
                _rpsBussiness.BestFitMode = BestFitMode.BestFitResizePopup;
                _rpsBussiness.View.OptionsView.ShowIndicator = false;
                _rpsBussiness.DisplayMember = "VoucherTypeName";
                _rpsBussiness.ValueMember = "VoucherTypeId";
            }
        }

       

        /// <summary>
        /// Sets the automatic businesses.
        /// </summary>
        /// <value>
        /// The automatic businesses.
        /// </value>
        public IList<AutoBusinessModel> AutoBusinesses
        {
            set
            {
                _rpsAutoBusinesses.DataSource = value;
                _rpsAutoBusinesses.PopulateViewColumns();
                var colColection = new List<XtraColumn>();
                colColection.Clear();

                colColection.Add(new XtraColumn
                {
                    ColumnName = "AutoBusinessId",
                    ColumnCaption = "Mã nghiệp vụ",
                    ColumnPosition = 1,
                    ColumnVisible = false,
                    ColumnWith = 100,
                    Alignment = HorzAlignment.Center
                });

                colColection.Add(new XtraColumn { ColumnName = "AutoBusinessCode", ColumnCaption = "Mã ĐK", ToolTip = "Mã định khoản tự động", ColumnPosition = 1, ColumnVisible = true, ColumnWith = 100 });
                colColection.Add(new XtraColumn { ColumnName = "AutoBusinessName", ColumnCaption = "Tên ĐK", ToolTip = "Tên định khoản tự động", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 300 });
                colColection.Add(new XtraColumn { ColumnName = "RefTypeId", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "UnitId", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "VoucherTypeId", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "DebitAccountNumber", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "CreditAccountNumber", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "Description", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "IsActive", ColumnVisible = false });


                foreach (var column in colColection)
                {
                    if (column.ColumnVisible)
                    {
                        _rpsAutoBusinessesView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].Width = column.ColumnWith;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].ToolTip = column.ToolTip;
                    }
                    else _rpsAutoBusinessesView.Columns[column.ColumnName].Visible = false;
                }
                _rpsAutoBusinesses.BestFitMode = BestFitMode.BestFitResizePopup;
                _rpsAutoBusinesses.DisplayMember = "AutoBusinessName";
                _rpsAutoBusinesses.ValueMember = "AutoBusinessId";
                _rpsAutoBusinesses.View.ActiveFilterString = "[RefTypeId]=" + RefTypeId;
                _rpsAutoBusinesses.View.OptionsView.ShowIndicator = false;
                _rpsAutoBusinesses.View.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                _rpsAutoBusinesses.View.OptionsView.ShowHorizontalLines = DefaultBoolean.False;
            }
        }


        /// <summary>
        /// Sets the inventory items.
        /// </summary>
        /// <value>
        /// The inventory items.
        /// </value>
        public IList<InventoryItemModel> InventoryItems
        {
            set
            {
                _rpsInventoryItem.DataSource = value;
                _rpsInventoryItem.PopulateViewColumns();
                var colColection = new List<XtraColumn>();
                colColection.Clear();

                colColection.Add(new XtraColumn { ColumnName = "InventoryItemCode", ColumnCaption = "Mã vật tư", ToolTip = "Mã vật tư", ColumnPosition = 1, ColumnVisible = true, ColumnWith = 100, Alignment = HorzAlignment.Center });
                colColection.Add(new XtraColumn { ColumnName = "InventoryItemName", ColumnCaption = "Tên vật tư", ToolTip = "Tên vật tư", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 100, Alignment = HorzAlignment.Center });
                colColection.Add(new XtraColumn { ColumnName = "InventoryItemId", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "IsActive", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "AccountCode", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "Unit", ColumnCaption = "", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "UnitId", ColumnCaption = "", ColumnVisible = false });

                foreach (var column in colColection)
                {
                    if (column.ColumnVisible)
                    {
                        _rpsInventoryItemView.Columns[column.ColumnName].ToolTip = column.ToolTip;
                        _rpsInventoryItemView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        _rpsInventoryItemView.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                        _rpsInventoryItemView.Columns[column.ColumnName].Width = column.ColumnWith;
                    }
                    else _rpsInventoryItemView.Columns[column.ColumnName].Visible = false;
                }
                _rpsInventoryItem.BestFitMode = BestFitMode.BestFitResizePopup;
                _rpsInventoryItem.View.OptionsView.ShowIndicator = false;
                //    _rpsInventoryItem.View.ActiveFilterString = "[BudgetItemType] >=3";
                _rpsInventoryItem.View.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                _rpsInventoryItem.DisplayMember = "InventoryItemCode";
                _rpsInventoryItem.ValueMember = "InventoryItemId";
            }
        }

        #endregion

        #region Data


        #endregion

        #region Events

        private void cboObjectCategory_EditValueChanged_1(object sender, EventArgs e)
        {
            try
            {
                SetObjectInfo(null, null, null, null, null);
                grdObjectCode.Enabled = true;
                var categoryId = (int)cboObjectCategory.GetColumnValue("ObjectCategoryId");
                switch (categoryId)
                {
                    case 3:
                        {
                            _customersPresenter.GetAll();
                            break;
                        }
                    case 0:
                        {
                            _vendorsPresenter.GetAll();
                            break;
                        }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void grdObjectCode_EditValueChanged_1(object sender, EventArgs e)
        {
            try
            {
                var categoryId = (int)cboObjectCategory.GetColumnValue("ObjectCategoryId");
                switch (categoryId)
                {
                    case 3:
                        {
                            var row = (CustomerModel)grdObjectCode.GetSelectedDataRow();
                            if (row != null)
                                SetObjectInfo(row.Name, row.ContactName, row.Address, null, "");//row.TaxCode
                            break;
                        }
                    case 0:
                        {
                            var row = (VendorModel)grdObjectCode.GetSelectedDataRow();
                            if (row != null)
                                SetObjectInfo(row.Name, row.ContactName, row.Address, null, "");
                            break;
                        }
                    //case 1:
                    //    {
                    //        var row = (EmployeeModel)grdObjectCode.GetSelectedDataRow();
                    //        if (row != null)
                    //            SetObjectInfo(row.EmployeeName, null, row.Address, null, null);
                    //        break;
                    //    }
                    //case 2:
                    //    {
                    //        var row = (AccountingObjectModel)grdObjectCode.GetSelectedDataRow();
                    //        if (row != null)
                    //            SetObjectInfo(row.FullName, row.ContactName, row.ContactAddress, null, row.TaxCode);
                    //        break;
                    //    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Sets the object information.
        /// </summary>
        /// <param name="objectName">Name of the object.</param>
        /// <param name="trader">The trader.</param>
        /// <param name="address">The address.</param>
        /// <param name="description">The description.</param>
        /// <param name="taxCode">The tax code.</param>
        private void SetObjectInfo(string objectName, string trader, string address, string description, string taxCode)
        {
            cboObjectName.Text = objectName;
            txtContactName.Text = trader;
            txtAddress.Text = address;
            txtTaxCode.Text = taxCode;
        }

     

        /// <summary>
        /// Handles the ValidateRow event of the gridViewDetail control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="ValidateRowEventArgs"/> instance containing the event data.</param>
        private void gridViewDetail_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            try
            {
                //    ItemTransactionDetails 
                var inventoryItemIdCol = gridViewDetail.Columns["InventoryItemId"];
                var accountNumberCol = gridViewDetail.Columns["AccountNumber"];
                var accountNumberVatCol = gridViewDetail.Columns["AccountNumberVat"];
                var amountrVatCol = gridViewDetail.Columns["AmountVat"];
                var correspondingAccountNumberCol = gridViewDetail.Columns["CorrespondingAccountNumber"];
                var quantityCol = gridViewDetail.Columns["Quantity"];
          //      var colAmountExchange = gridViewDetail.Columns["AmountExchange"];
                var amountOcCol = gridViewDetail.Columns["AmountOc"];

                var inventoryItemId = (int)gridViewDetail.GetRowCellValue(e.RowHandle, inventoryItemIdCol);
                var accountNumber = (string)gridViewDetail.GetRowCellValue(e.RowHandle, accountNumberCol);
                var accountNumberVat = (string)gridViewDetail.GetRowCellValue(e.RowHandle, accountNumberVatCol);
                var amountVat = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, amountrVatCol); 
                var correspondingAccountNumber = (string)gridViewDetail.GetRowCellValue(e.RowHandle, correspondingAccountNumberCol);
                var quantity = (int)gridViewDetail.GetRowCellValue(e.RowHandle, quantityCol);
             //   var amountExchange = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, colAmountExchange);
                var amountOc = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, amountOcCol);
                if ((amountVat > 0) && (string.IsNullOrEmpty(accountNumberVat) || accountNumberVat.Equals("")))
                {
                    e.Valid = false;
                    gridViewDetail.SetColumnError(accountNumberVatCol, "Bạn chưa định khoản cho tiền thuế" );
                }
                if (inventoryItemId <= 0)
                { 
                    e.Valid = false;
                    gridViewDetail.SetColumnError(inventoryItemIdCol, "Bạn chưa chọn vật tư");
                }
                if (string.IsNullOrEmpty(accountNumber) || accountNumber.Equals(""))
                {
                    e.Valid = false;
                    gridViewDetail.SetColumnError(accountNumberCol, ResourceHelper.GetResourceValueByName("ResFArmortizationDetailAccountNumber"));
                }
                if (string.IsNullOrEmpty(correspondingAccountNumber) || correspondingAccountNumber.Equals(""))
                {
                    e.Valid = false;
                    gridViewDetail.SetColumnError(correspondingAccountNumberCol, ResourceHelper.GetResourceValueByName("ResFArmortizationDetailCorrespondingAccountNumber"));
                }
                if (quantity <= 0)
                {
                    e.Valid = false;
                    gridViewDetail.SetColumnError(quantityCol, ResourceHelper.GetResourceValueByName("ResFArmortizationDetailQuantity"));
                }
             //   if (amountExchange < 0)
             //   {
                    //    e.Valid = false;
                    //    gridViewDetail.SetColumnError(colAmountExchange, ResourceHelper.GetResourceValueByName("ResFArmortizationDetailExchangeRate"));
             //   }
                if (amountOc < 0)
                {
                    e.Valid = false;
                    gridViewDetail.SetColumnError(amountOcCol, ResourceHelper.GetResourceValueByName("ResFArmortizationDetailAmountOc"));
                }
                var colAccountNumber = gridViewDetail.Columns["AccountNumber"];
                var colCorrespondingAccountNumber = gridViewDetail.Columns["CorrespondingAccountNumber"];
                var valueAccountNumber = (string)gridViewDetail.GetRowCellValue(e.RowHandle, colAccountNumber);
                var mdAccount = (AccountModel)_rpsCorrespondingAccountNumber.GetRowByKeyValue(valueAccountNumber);
              //  var colBudgetSourceCode = gridViewDetail.Columns["BudgetSourceCode"];
             //   //var colBudgetItemCode = gridViewDetail.Columns["BudgetItemCode"];
              //  var valBudgetSourceCode = (string)gridViewDetail.GetRowCellValue(e.RowHandle, colBudgetSourceCode);
              //  var valBudgetItemCode = (string)gridViewDetail.GetRowCellValue(e.RowHandle, colBudgetItemCode);

                var valCorrespondingAccountNumber = (string)gridViewDetail.GetRowCellValue(e.RowHandle, colCorrespondingAccountNumber);

                var mdAccountCor = (AccountModel)_rpsCorrespondingAccountNumber.GetRowByKeyValue(valCorrespondingAccountNumber);
                IList<AccountModel> aListAccount = new List<AccountModel>();
                if (mdAccount != null)
                {
                    aListAccount.Add(mdAccount);
                }
                if (mdAccountCor != null)
                {
                    aListAccount.Add(mdAccountCor);
                }
                foreach (var strAccount in aListAccount)
                {
                    //if (!strAccount.IsDetail)
                    //{
                    //    e.Valid = false;
                    //    if (strAccount == mdAccount)
                    //    {
                    //        e.Valid = false;
                    //        gridViewDetail.SetColumnError(colAccountNumber, "Bạn chọn TK Nợ chi tiết hơn");
                    //    }
                    //    else
                    //    {
                    //        e.Valid = false;
                    //        gridViewDetail.SetColumnError(colCorrespondingAccountNumber, "Bạn chọn TK Có chi tiết hơn");
                    //    }
                    //}
                    //if (strAccount.IsBudgetSource && valBudgetSourceCode == null)
                    //{
                    //    e.Valid = false;
                    //    gridViewDetail.SetColumnError(colBudgetSourceCode, "Bạn chưa chọn nguồn vốn");
                    //}
                    //if (strAccount.IsBudgetItem && valBudgetItemCode == null)
                    //{
                    //    e.Valid = false;
                    //    gridViewDetail.SetColumnError(colBudgetItemCode, "Bạn chưa Mục/TM");

                    //}

                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(),
                    ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// Handles the CellValueChanged event of the gridViewDetail control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="CellValueChangedEventArgs"/> instance containing the event data.</param>
        private void gridViewDetail_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            try
            {
                GridColumn exchangeRateCol;
                switch (e.Column.FieldName)
                {
                    case "Quantity":
                        var quantityCol = gridViewDetail.Columns["Quantity"];
                        var quantity = (int)gridViewDetail.GetRowCellValue(e.RowHandle, quantityCol);                      
                        var unitPriceOCCol = gridViewDetail.Columns["Price"];
                        var unitPriceOC = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, unitPriceOCCol);
                        var amountCol = gridViewDetail.Columns["AmountOc"];
                        gridViewDetail.SetRowCellValue(e.RowHandle, amountCol, quantity * unitPriceOC);
                        break;
                    case "TaxRate":
                        var taxRateCol = gridViewDetail.Columns["TaxRate"];
                        var taxRate = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, taxRateCol);
                         amountCol = gridViewDetail.Columns["AmountOc"];
                        var amount = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, amountCol);
                        var amountVatCol = gridViewDetail.Columns["AmountVat"];
                        gridViewDetail.SetRowCellValue(e.RowHandle, amountVatCol, amount * taxRate /100);
                        break;
                    case "Price":
                        quantityCol = gridViewDetail.Columns["Quantity"];
                        amountCol = gridViewDetail.Columns["AmountOc"];
                        unitPriceOCCol = gridViewDetail.Columns["Price"];
                        quantity = (int)gridViewDetail.GetRowCellValue(e.RowHandle, quantityCol);
                        unitPriceOC = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, unitPriceOCCol);
                        gridViewDetail.SetRowCellValue(e.RowHandle, amountCol, quantity * unitPriceOC);
                        break;
                    case "AmountOc":
                        if ((decimal)e.Value > 0)
                        {

                         //   amountExchangeCol = gridViewDetail.Columns["AmountExchange"];
                         //   exchangeRateCol = gridViewMaster.Columns["ExchangeRate"];
                            //var exchangeRate = decimal.Parse(gridViewMaster.GetRowCellValue(e.RowHandle, exchangeRateCol).ToString().Replace(".", ","));
                         //   exchangeRate = (decimal)gridViewMaster.GetFocusedRowCellValue(exchangeRateCol);
                         //   if (exchangeRate > 0)
                          //      gridViewDetail.SetRowCellValue(e.RowHandle, amountExchangeCol, (decimal)e.Value / exchangeRate);
                        }
                        break;
                    //case "ExchangeRate":
                    //    if (decimal.Parse(e.Value.ToString().Replace(".", ",")) > 0)
                    //    {
                    //        amountExchangeCol = gridViewDetail.Columns["AmountExchange"];
                    //        amountCol = gridViewDetail.Columns["AmountOc"];
                    //        var amount = (decimal)gridViewDetail.GetRowCellValue(e.RowHandle, amountCol);

                    //        if (amount > 0)
                    //            gridViewDetail.SetRowCellValue(e.RowHandle, amountExchangeCol, amount / decimal.Parse(e.Value.ToString().Replace(".", ",")));
                    //    }
                    //    break;
                    case "AutoBusinessId":
                        {
                            var rowHandle = gridViewDetail.FocusedRowHandle;
                            if (gridViewDetail.GetRowCellValue(rowHandle, "AutoBusinessId") != null)
                            {
                                var autoBusinessId = (int)gridViewDetail.GetRowCellValue(rowHandle, "AutoBusinessId");
                                var autoBusiness = (AutoBusinessModel)_rpsAutoBusinesses.GetRowByKeyValue(autoBusinessId);
                                gridViewDetail.SetRowCellValue(rowHandle, "AccountNumber", autoBusiness.DebitAccountNumber);
                                gridViewDetail.SetRowCellValue(rowHandle, "CorrespondingAccountNumber", autoBusiness.CreditAccountNumber);
                                gridViewDetail.SetRowCellValue(rowHandle, "VoucherTypeId", autoBusiness.VoucherTypeId);
                                gridViewDetail.SetRowCellValue(rowHandle, "Description", autoBusiness.Description);
                            }
                        }
                        break;
                    case "InventoryItemId":
                        {
                            var rowHandle = gridViewDetail.FocusedRowHandle;

                            if (gridViewDetail.GetRowCellValue(rowHandle, "InventoryItemId") != null)
                            {
                                if ((int)e.Value > 0)
                                {
                                    var inventInventoryItemId =
                                        (int)gridViewDetail.GetRowCellValue(rowHandle, "InventoryItemId");
                                    var inventoryItem =
                                        (InventoryItemModel)_rpsInventoryItem.GetRowByKeyValue(inventInventoryItemId);
                                    gridViewDetail.SetRowCellValue(rowHandle, "Description",
                                                                   "Nhập kho vật tư " + inventoryItem.InventoryItemName);
                                    gridViewDetail.SetRowCellValue(rowHandle, "AccountNumber", "153");
                                }
                            }
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(),
                    ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        #endregion  
    
    

        public IList<AutoBusinessModel> AutoBusinesss
        {
            set
            {
                _rpsAutoBusinesses.DataSource = value;
                _rpsAutoBusinesses.PopulateViewColumns();
                var colColection = new List<XtraColumn>();
                colColection.Clear();

                colColection.Add(new XtraColumn
                {
                    ColumnName = "AutoBusinessId",
                    ColumnCaption = "Mã nghiệp vụ",
                    ColumnPosition = 1,
                    ColumnVisible = false,
                    ColumnWith = 100,
                    Alignment = HorzAlignment.Center
                });

                colColection.Add(new XtraColumn { ColumnName = "AutoBusinessCode", ColumnCaption = "Mã ĐK", ToolTip = "Mã định khoản tự động", ColumnPosition = 1, ColumnVisible = true, ColumnWith = 100 });
                colColection.Add(new XtraColumn { ColumnName = "AutoBusinessName", ColumnCaption = "Tên ĐK", ToolTip = "Tên định khoản tự động", ColumnPosition = 2, ColumnVisible = true, ColumnWith = 300 });
                colColection.Add(new XtraColumn { ColumnName = "RefTypeId", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "VoucherTypeId", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "DebitAccountNumber", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "CreditAccountNumber", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "Description", ColumnVisible = false });
                colColection.Add(new XtraColumn { ColumnName = "IsActive", ColumnVisible = false });


                foreach (var column in colColection)
                {
                    if (column.ColumnVisible)
                    {
                        _rpsAutoBusinessesView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].Width = column.ColumnWith;
                        _rpsAutoBusinessesView.Columns[column.ColumnName].ToolTip = column.ToolTip;
                    }
                    else _rpsAutoBusinessesView.Columns[column.ColumnName].Visible = false;
                }
                _rpsAutoBusinesses.BestFitMode = BestFitMode.BestFitResizePopup;
                _rpsAutoBusinesses.DisplayMember = "AutoBusinessName";
                _rpsAutoBusinesses.ValueMember = "AutoBusinessId";
                _rpsAutoBusinesses.View.ActiveFilterString = "[RefTypeId]=" + RefTypeId;
                _rpsAutoBusinesses.View.OptionsView.ShowIndicator = false;
                _rpsAutoBusinesses.View.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                _rpsAutoBusinesses.View.OptionsView.ShowHorizontalLines = DefaultBoolean.False;
            }
        }

      
    }
    /// <summary>
    /// ObjectCategory
    /// </summary>
    public class ObjectCategory
    {
        /// <summary>
        /// Gets or sets the object category identifier.
        /// </summary>
        /// <value>
        /// The object category identifier.
        /// </value>
        public int ObjectCategoryId { get; set; }

        /// <summary>
        /// Gets or sets the name of the object category.
        /// </summary>
        /// <value>
        /// The name of the object category.
        /// </value>
        public string ObjectCategoryName { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectCategory"/> class.
        /// </summary>
        /// <param name="objectCategoryId">The object category identifier.</param>
        /// <param name="objectCategoryName">Name of the object category.</param>
        public ObjectCategory(int objectCategoryId, string objectCategoryName)
        {
            ObjectCategoryId = objectCategoryId;
            ObjectCategoryName = objectCategoryName;
        }
    }
}